<template>
  <!-- 放置弹层组件 -->
  <el-dialog :title="showTitle" :visible="showDialog" @close="Cancel">
    <!-- 表单数据 -->
    <!-- label-width设置label的库宽度 -->
    <el-form label-width="120px" :model="formDate" :rules="rules" ref="deptForm">
      <el-form-item label="部门名称" prop="name">
        <el-input style="width: 80%" placeholder="1-50个字符" v-model="formDate.name"></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input style="width: 80%" placeholder="1-50个字符" v-model="formDate.code"></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select style="width: 80%" placeholder="请选择" v-model="formDate.manager" @focus="getEmployeeSimple">
            <el-option v-for="item in peoples" :key="item.id" :label="item.username" :value="item.username"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
          v-model="formDate.introduce"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 确定和消息 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="Cancel">取消</el-button>
        <el-button size="small" type="primary" @click="submit">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartDatail, updateDepart } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    treeNode: {
      type: Object,
      default: null
    },
  },
  data() {
    // 检查同级部门下是否有重复的部门名称
    const checkNameRepeat = async(rule, value, callback) => {
        // 先要获取最新的组织架构数据
        const { depts } = await getDepartments()
        // depts是所有的部门数据
        let isRepeat = false
         if (this.formDate.id) {
            isRepeat = depts.filter(item => item.id !== this.formDate.id && item.pid === this.treeNode.pid)
            .some(item => item.name === value)
         } else {
            isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value)
         }
            // 如果isRepeat为true 表示找到了一样的名字
            isRepeat ? callback(new Error(`同级部门下已经有${value}的部门了`)) : callback()
    }
    const checkCodeRepeat = async (rule, value, callback) => {
        const { depts } = await getDepartments()
        // 要求编码和所有的部门编码都不能重复由于历史数据由可能没有code所以所这里加一个强制性条件就是value值不为空
        let isRepeat = false
        if (this.formDate.id) {
            isRepeat = depts.some(item => item.id !== this.formDate.id && item.code === value && value)
        } else {
            isRepeat = depts.some(item => item.coed === value && value)
        }
        isRepeat ? callback(new Error(`组织架构下已经存在了这个${value}编码了`)) : callback()
    }
    return {
      formDate: {
        name: "", // 部门名称
        code: "", // 部门编码
        manager: "", // 部门管理者
        introduce: "", // 部门介绍
      },
      peoples: [], // 接收获取的员工简单列表的数据
      rules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门名称要求1-50个字符",
            trigger: "blur",
          },
          {
            trigger: "blur",
            validator: checkNameRepeat  // 自定义函数的形式校验
          }
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门编码要求1-50个字符",
            trigger: "blur",
          },
          {
            trigger: "blur",
            validator: checkCodeRepeat
          }
        ],
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" },
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          {
            min: 1,
            max: 300,
            message: "部门编码要求1-300个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 获取员工列表的简单列表
    async getEmployeeSimple () {
        this.peoples = await getEmployeeSimple()
    },
    submit () {
        this.$refs.deptForm.validate(async isOk => {
            if (isOk) {
                if (this.formDate.id) {
                    // 修改部门详情
                    await updateDepart(this.formDate)
                    // 消息通知
                    this.$message.success('部门详情修改成功')
                } else {
                    // 校验通过后添加
                    await addDepartments({ ...this.formDate, pid: this.treeNode.id })
                    // 消息通知
                    this.$message.success('部门添加成功')
                } 
                // 初始化数据
                this.$emit('addDepts')
                // 通知父组件关闭弹出层
                this.$emit('update:showDialog', false)
            }
        })
    },
    Cancel () {
        // 因为resetFields只能重置表单上的数据非表单上的比如编辑中id不能重置
        this.formDate = {
            name: '',
            code: '',
            manager: '',
            introduce: ''
        }
        this.$refs.deptForm.resetFields() // 重置字段
        this.$emit('update:showDialog', false)
    },
    // 获取部门详情
    async getDepartDatail (id) {
        const res  = await getDepartDatail(id)
        this.formDate = res
    } 
  },
  computed: {
    showTitle () {
        return this.formDate.id ? '编辑部门' : '新增子部门'
    }
  }
};
</script>

<style>
</style>